import { TurboModule } from '@rnoh/react-native-openharmony/ts';
import { vibrator } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

const VIBRATION_PRESET_MAP: Map<number, string> = new Map([
  [1519, 'haptic.effect.soft'],    
  [1520, 'haptic.effect.hard'],    
  [1521, 'haptic.notice.fail'],    
]);

export class RNVibrationFeedbackModule extends TurboModule {
  public static readonly NAME = 'RNVibrationFeedback';
  vibrateWith(id: number): void {
    const effectId = VIBRATION_PRESET_MAP.get(id);
    const finalEffectId = effectId || 'haptic.effect.soft';
      if (finalEffectId){
        this.vibrateWithPresetInternal(finalEffectId);
      }
  }

  private vibrateWithPresetInternal(effectId: string): void {
    try {
      const isSupported = vibrator.isSupportEffectSync(effectId);
      if (isSupported) {
        this.startPresetVibration(effectId);
      }
    } catch (error) {
      let e: BusinessError = error as BusinessError;
      console.error(`[RNVibrationFeedback] isSupportEffectSync error: ${e.code}, ${e.message}`);
    }
  }

  private startPresetVibration(effectId: string): void {
    try {
      vibrator.startVibration({
        type: 'preset',
        effectId: effectId,
        count: 1,
      }, {
        usage: 'touch'
      }, (error: BusinessError) => {
        if (error) {
          console.error(`[RNVibrationFeedback] Preset vibration failed: ${error.code}, ${error.message}`);
        }
      });
    } catch (error) {
      let e: BusinessError = error as BusinessError;
      console.error(`[RNVibrationFeedback] startPresetVibration error: ${e.code}, ${e.message}`);
    }
  }

  isSupportEffect(effectId: string): boolean {
    try {
      return vibrator.isSupportEffectSync(effectId);
    } catch (error) {
      let e: BusinessError = error as BusinessError;
      console.error(`[RNVibrationFeedback] isSupportEffect error: ${e.code}, ${e.message}`);
      return false;
    }
  }
}
